<template>
  <div class="app">
    <router-view />
  </div>
</template>

<script>
  import { computed, getCurrentInstance, onMounted, onUnmounted, provide } from 'vue'
  import { useStore } from 'vuex'

  export default {
    name: 'app',
    setup() {
      // 获取vue实例 传递给所有子组件
      const self = getCurrentInstance().appContext.config.globalProperties
      provide('$self',self)
      // console.log(getCurrentInstance())

      const store = useStore()
      // 视图改变防抖延时器
      let resizeTime = null
      onMounted(() => {
        handleWindowResize()
        window.addEventListener('resize', () => {
          if (resizeTime) {
            clearTimeout(resizeTime)
          }
          resizeTime = setTimeout(() => {
            handleWindowResize()
          }, 500)
        })
      })
      onUnmounted(() => {
        window.removeEventListener('resize', () => {
          handleWindowResize()
        })
      })
      function handleWindowResize() {
        /**
         * window.matchMedia 返回是否符合给定的媒体查询条件
         * @query {string} 参数可以是任何一个 CSS @media 规则 的特性, 如 min-height, min-width, orientation 等
         */
        const matchMedia = window.matchMedia
        if (matchMedia('(max-width: 768px)').matches) {
          store.commit('layout/setDevice', 'Mobile')
          // 手机
          // 不显示面包屑
          store.dispatch('layout/setSetting', { headerBreadcrumbShow: false })
          // 不显示全屏按钮
          store.dispatch('layout/setSetting', { headerFullscreenShow: false })
        } else if (matchMedia('(max-width: 1024px)').matches) {
          store.commit('layout/setDevice', 'Tablet')
          // 平板
          // 显示面包屑
          store.dispatch('layout/setSetting', { headerBreadcrumbShow: true })
          // 不显示全屏按钮
          store.dispatch('layout/setSetting', { headerFullscreenShow: false })
          // 菜单收起
          store.dispatch('layout/setCollapse', true)
        } else {
          store.commit('layout/setDevice', 'Desktop')
          // 桌面pc
          // 显示面包屑
          store.dispatch('layout/setSetting', { headerBreadcrumbShow: true })
          // 显示全屏按钮
          store.dispatch('layout/setSetting', { headerFullscreenShow: true })
          // 菜单放开
          store.dispatch('layout/setCollapse', false)
        }
      }
      return {
        cachedViews: computed(() => store.state.page.cachedViews)
      }
    }
  }
</script>

<style>
</style>
